package cn.aifeix.lxyc.service.impl;

import cn.aifeix.lxyc.domain.ServicePlan;
import cn.aifeix.lxyc.feign.ShopService;
import cn.aifeix.lxyc.domain.Point;
import cn.aifeix.lxyc.domain.Shop;
import cn.aifeix.lxyc.domain.User;
import cn.aifeix.lxyc.dto.UserAddressDto;
import cn.aifeix.lxyc.enums.GlobalErrorCodeEnum;
import cn.aifeix.lxyc.mapper.UserMapper;
import cn.aifeix.lxyc.result.JSONResult;
import cn.aifeix.lxyc.service.IServicePlanService;
import cn.aifeix.lxyc.service.IUserService;
import cn.aifeix.lxyc.utils.AssertUtil;
import cn.aifeix.lxyc.utils.DistanceUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author director
 * @since 2022-12-09
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    @Autowired
    private ShopService shopService;

    @Autowired
    private IServicePlanService servicePlanService;

    /**
     * 获取附近门店
     * @param userAddressDto
     * @return
     */
    @Override
    public Shop getNearbyStores(UserAddressDto userAddressDto) {
        String address = userAddressDto.getAddress();
        // 参数校验
        AssertUtil.isNotEmpty(address, GlobalErrorCodeEnum.ERROR);
        JSONResult JSONResultList = shopService.list();
        AssertUtil.isNotNull(JSONResultList,GlobalErrorCodeEnum.ERROR);
        AssertUtil.isNotNull(JSONResultList.isSuccess(), GlobalErrorCodeEnum.ERROR);
        Object data = JSONResultList.getData();
        AssertUtil.isNotNull(data, GlobalErrorCodeEnum.ERROR);
        // 转为集合
        List<Shop> shops = JSONObject.parseArray(JSONObject.toJSONString(data), Shop.class);
        // 调用工具类匹配最近门店
        Point point = DistanceUtil.getPoint(address);
        Shop shop = DistanceUtil.getNearestShop(point, shops);
        AssertUtil.isNotNull(shop,GlobalErrorCodeEnum.ERROR);
        return shop;
    }

    /**
     * 根据用户车型推荐对应方案
     * @param userAddressDto
     * @return
     */
    @Override
    public ServicePlan getServicePlan(UserAddressDto userAddressDto) {
        String carTypeName = userAddressDto.getCarTypeName();
        Long serviceId = userAddressDto.getServiceId();
        AssertUtil.isNotEmpty(carTypeName, GlobalErrorCodeEnum.ERROR);
        AssertUtil.isNotNull(serviceId ,GlobalErrorCodeEnum.ERROR);
        Wrapper<ServicePlan> wrapper = new EntityWrapper<>();
        wrapper.eq("car_type_name", carTypeName);
        wrapper.eq("service_id", serviceId);
        ServicePlan servicePlan = servicePlanService.selectOne(wrapper);
        AssertUtil.isNotNull(servicePlan, GlobalErrorCodeEnum.ERROR);
        return servicePlan;
    }
}
